﻿namespace Digitalmes.Infrastructure.Common.SerialPorts;

internal sealed class SerialPortsSwitch : ISerialPortsSwitch
{
    private readonly SerialPortsManager _manager;

    public SerialPortsSwitch(SerialPortsManager manager)
    {
        _manager = manager;
    }

    public (bool ok, string? portName, Exception? ex) Open()
    {
        var serialPort = _manager.GetSerialPort();

        try
        {
            serialPort?.Open();

            return (true, serialPort?.PortName, default);
        }
        catch (Exception ex)
        {
            return (false, serialPort?.PortName, ex);
        }
    }

    public (bool ok, Exception? ex) Open(string portName)
    {
        var serialPort = _manager.GetSerialPort(portName);

        try
        {
            serialPort?.Open();

            return (true, default);
        }
        catch (Exception ex)
        {
            return (false, ex);
        }
    }

    public (bool ok, Exception? ex) OpenViaPurpose(string purpose)
    {
        var serialPort = _manager.GetSerialPortViaPurpose(purpose);

        try
        {
            serialPort?.Open();

            return (true, default);
        }
        catch (Exception ex)
        {
            return (false, ex);
        }
    }

    public (bool ok, Exception? ex) Close()
    {
        var serialPort = _manager.GetSerialPort();

        try
        {
            serialPort?.Close();

            return (true, default);
        }
        catch (Exception ex)
        {
            return (false, ex);
        }
    }

    public (bool ok, Exception? ex) Close(string portName)
    {
        var serialPort = _manager.GetSerialPort(portName);

        try
        {
            serialPort?.Close();

            return (true, default);
        }
        catch (Exception ex)
        {
            return (false, ex);
        }
    }

    public (bool ok, Exception? ex) CloseViaPurpose(string purpose)
    {
        var serialPort = _manager.GetSerialPortViaPurpose(purpose);

        try
        {
            serialPort?.Close();

            return (true, default);
        }
        catch (Exception ex)
        {
            return (false, ex);
        }
    }
}
